export * from "./config";
import { initMap, addBoxToMap } from "./Map";
import { createBox } from "./Box";
import { render } from "./renderer";
import { addTicker, removeTicker } from "./ticker";
import { intervalTimer } from "./utils";
import { eliminateLine } from "./eliminateLine";
import { gameState, resetSpeed } from "./gameState";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { createVNode } from 'vue';
import { Modal } from 'ant-design-vue';
import {
  hitBottomBoundary,
  hitLeftBoundary,
  hitRightBoundary,
  hitBottomBox,
  hitLeftBox,
} from "./hit";

let activeBox = null;
let _map = null;

export function initGame(map) {
  initMap(map);
  _map = map;
}

export function startGame() {
  activeBox = addBox();
  addTicker(handleTicker);
  window.addEventListener("keyup", (e) => {
    if (e.code === "ArrowDown") {
      resetSpeed();
    }
  });
  window.addEventListener("keydown", (e) => {
    switch (e.code) {
      case "ArrowLeft":
        leftMoveBox();
        break;
      case "ArrowRight":
        rightMoveBox();
        break;
      case "ArrowDown":
        // upSpeed();
        bottomMoveBox()
        break;
      case "ArrowUp":
        toprotate()
        break;

      case "Space":
        toprotate()
        break;
    }
  });
}

const needDownMove = intervalTimer();
function handleTicker(n) {
  if (needDownMove(n, gameState.downIntervalTime)) {
    bottomMoveBox();
  }
  render(activeBox, _map);
}

export function toprotate() {
  activeBox.rotate();
}

export function rightMoveBox() {
  if (hitRightBoundary(activeBox)) return;
  activeBox.x++;
}

export function leftMoveBox() {
  if (hitLeftBoundary(activeBox) || hitLeftBox(activeBox, _map)) return;
  activeBox.x--;
}

export function bottomMoveBox() {
  // 碰到边界的时候不可以在移动了!!
  if (hitBottomBoundary(activeBox) || hitBottomBox(activeBox, _map)) {
    resetSpeed();

    addBoxToMap(activeBox, _map);
    eliminateLine(_map);

    if (activeBox.y < 0) {
      gameOver();
      return;
    }

    activeBox = addBox();
    return;
  }

  activeBox.y++;
}

 export function addBox() {
  return createBox();
}

function gameOver() {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { style: 'color:red;' }, 'oh no ！你死啦'),
    onOk() {
      location.reload();
    },
    onCancel() {
      location.reload();
    },
    class: 'test',
  });
  removeTicker(handleTicker);
}
